package com.zjhb.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.zjhb.common.controller.ExcelUtil;
import com.zjhb.common.controller.ExportBean;
import com.zjhb.common.dao.BaseDao;
import com.zjhb.common.dao.Page;
import com.zjhb.common.enumutil.UserStatus;
import com.zjhb.common.enumutil.UserTypes;
import com.zjhb.common.util.BeanCopy;
import com.zjhb.common.util.JwtUser;
import com.zjhb.common.util.ResourceUtil;
import com.zjhb.common.util.ResponseUtil;
import com.zjhb.common.util.StringMyUtil;
import com.zjhb.common.util.TokenUtil;
import com.zjhb.entity.DepartmentEntity;
import com.zjhb.entity.MenuEntity;
import com.zjhb.entity.UserEntity;

import param.UserParam;

@RestController
@RequestMapping("/root")
public class RootController {

	@Autowired
	private BaseDao baseDao;

	@PostMapping("/login")
	public JSONObject checkuser(HttpServletRequest req, HttpServletResponse response) {
		// 语言选择
		JSONObject j = new JSONObject();
		// 验证码
		Criteria crt = baseDao.getCriteria(UserEntity.class);
		String name = req.getParameter("userName");
		String password = req.getParameter("password");
		crt.add(Restrictions.eq("name", name)).add(Restrictions.eq("password", password));
		List<UserEntity> list = crt.list();
		if (list.size() == 0) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "用户或密码不正确", "");
			return j;
		} else {
			UserEntity user = list.get(0);
			if (user.getTypes().equals(UserTypes.Keep.getKey())) {
				j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "维修人员不允许登陆", "");
				return j;
			}
			if (user.getStatus().equals("0")) {
				j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "该账号已冻结", "");
				return j;
			}

			JwtUser jwtuser = new JwtUser();
			jwtuser.setId(user.getId());
			jwtuser.setName(user.getName());
			jwtuser.setUserType(user.getTypes());
			String departmentId = user.getDepatmentId();
			if (StringMyUtil.isNotEmpty(departmentId)) {
				DepartmentEntity de = baseDao.getById(DepartmentEntity.class, departmentId);
				jwtuser.setDepartId(departmentId);
				jwtuser.setDepartName(de.getName());
			}
			String token = TokenUtil.createJWT(jwtuser);
			jwtuser.setToken(token);
			jwtuser.setUserTypeDesc(UserTypes.parse(jwtuser.getUserType()).getValue());
			j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "登陆成功", jwtuser);
			return j;

		}
	}

	@PostMapping("user/add")
	public JSONObject addUser(UserEntity user, HttpServletRequest req) throws Exception {
		// 语言选择
		JSONObject j = new JSONObject();
		if (!ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
			return j;
		}
		if (user.getTypes().equals(UserTypes.Admin.getKey())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "当前系统只能存在一个管理员", "");
			return j;
		}

		if (StringMyUtil.isEmpty(user.getName()) || StringMyUtil.isEmpty(user.getPassword())
				|| StringMyUtil.isEmpty(user.getTypes())) {
			j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "名称角色必填", "");
			return j;
		}
		if (UserTypes.parse(user.getTypes()) == null) {
			j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "找不到该角色", "");
			return j;
		}
		if (UserTypes.Admin.getKey().equals(user.getTypes()) || UserTypes.Leader.getKey().equals(user.getTypes())) {
			user.setDepatmentId(null);
		}
		if (UserTypes.Base.getKey().equals(user.getTypes())) {
			if (StringMyUtil.isEmpty(user.getDepatmentId())) {
				j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "请选择部门", "");
				return j;
			}
		}
		if (StringMyUtil.isNotEmpty(user.getId())) {
			UserEntity bean = baseDao.getById(UserEntity.class, user.getId());
			BeanCopy.copyBean2Bean(bean, user);
			baseDao.update(bean);
		} else {
			user.setStatus("1");
			baseDao.save(user);

		}
		// 默认菜单
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	@PostMapping("user/delete/{id}")
	public JSONObject delete(@PathVariable String id) {
		JSONObject j = new JSONObject();
		if (id.equals(ResourceUtil.getCurrentUser().getId())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您不能删除自己", "");
			return j;
		}
		// 语言选择
		if (!ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
			return j;
		}

		UserEntity user = baseDao.getById(UserEntity.class, id);
		user.setStatus("0");
		baseDao.update(user);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;

		// 默认菜单

	}

	@RequestMapping("/user/list")
	public JSONObject userList(UserParam param, HttpServletRequest request, HttpServletResponse resp) throws Exception {
		// 语言选择
		if (!ResourceUtil.validate(request)) {
			return ResponseUtil.getMap(ResponseUtil.NOTOEKN_CODE, "用户未登录", "");
		}
		JSONObject j = new JSONObject();
		if (!ResourceUtil.getCurrentUser().getUserType().equals(UserTypes.Admin.getKey())) {
			j = ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
			return j;
		}
		Page<UserEntity> page = new Page<>();
		Criteria crt = baseDao.getCriteria(UserEntity.class);
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getRealName())) {
			crt.add(Restrictions.like("realName", param.getRealName(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getDepatmentId())) {
			crt.add(Restrictions.eq("depatmentId", param.getDepatmentId()));
		}
		if (StringMyUtil.isNotEmpty(param.getTypes())) {
			crt.add(Restrictions.eq("types", param.getTypes()));
		}
		crt.add(Restrictions.eq("status", "1"));
		crt.setMaxResults(param.getLimit());
		crt.setFirstResult(param.getOffset());
		crt.addOrder(Order.desc("status"));
		List<UserEntity> list = crt.list();
		if (list.size() > 0) {
			for (UserEntity entity : list) {
				entity.setStatusDesc(UserStatus.parse(entity.getStatus()).getValue());
				entity.setTypesDesc(UserTypes.parse(entity.getTypes()).getValue());
			}
		}
		Long totalNum = baseDao.getCount(crt);
		page.setRows(list);
		page.setTotal(totalNum);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", page);
		return j;
		// 默认菜单

	}

	@RequestMapping("/user/down")
	public void dwon(UserParam param, HttpServletRequest request, HttpServletResponse resp) throws Exception {
		// 语言选择
		if (!ResourceUtil.validate(request)) {
			return;
		}
    	Criteria crt = baseDao.getCriteria(UserEntity.class);
    	if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getRealName())) {
			crt.add(Restrictions.like("realName", param.getRealName(), MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getDepatmentId())) {
			crt.add(Restrictions.eq("depatmentId", param.getDepatmentId()));
		}
		if (StringMyUtil.isNotEmpty(param.getTypes())) {
			crt.add(Restrictions.eq("types", param.getTypes()));
		}
		crt.add(Restrictions.eq("status", "1"));
		List<UserEntity> list = crt.list();
		ExportBean<UserEntity> bean = new ExportBean<>();
		bean.setPoList(list);
		bean.setHeader(new String[] { "登陆账号", "真实姓名", "部门", "角色" });
		if (list.size() > 0) {
			for (UserEntity entity : list) {
				entity.setTypesDesc(UserTypes.parse(entity.getTypes()).getValue());
				if (StringMyUtil.isNotEmpty(entity.getDepatmentId())) {
					DepartmentEntity depart = baseDao.getById(DepartmentEntity.class, entity.getDepatmentId());
					entity.setDepatmentDesc(depart.getName());
				}

			}
		}
		OutputStream os = resp.getOutputStream();
		resp.setHeader("Content-Disposition",
				"attachment;filename=" + new String("用户.xls".getBytes("gb2312"), "ISO8859-1"));

		bean.setHeaderSize(4);
		bean.setTitle("用户");
		ExcelUtil.exportFromBean(bean, os);

	}

	@PostMapping("/menu")
	public JSONObject menu() {
		JSONObject j = new JSONObject();
		Criteria crt = baseDao.getCriteria(MenuEntity.class);
		Criteria crtSon = baseDao.getCriteria(MenuEntity.class);
		if (UserTypes.Admin.getKey().equals(ResourceUtil.getCurrentUser().getUserType())) {
			crt.add(Restrictions.isNull("parentId")).addOrder(Order.asc("seq"));
			crtSon.add(Restrictions.isNotNull("parentId")).addOrder(Order.asc("seq"));
		} else if (UserTypes.Base.getKey().equals(ResourceUtil.getCurrentUser().getUserType())) {
			crt.add(Restrictions.isNull("parentId")).add(Restrictions.eq("pub", "T")).addOrder(Order.asc("seq"));
			crtSon.add(Restrictions.isNotNull("parentId")).add(Restrictions.eq("pub", "T")).addOrder(Order.asc("seq"));
		} else if (UserTypes.Leader.getKey().equals(ResourceUtil.getCurrentUser().getUserType())) {
			crt.add(Restrictions.isNull("parentId")).add(Restrictions.eq("leader", "T")).addOrder(Order.asc("seq"));
			crtSon.add(Restrictions.isNotNull("parentId")).add(Restrictions.eq("leader", "T"))
					.addOrder(Order.asc("seq"));
		} else {
			j = ResponseUtil.getMap(ResponseUtil.PARAMETER_CODE, "异常", "");
			return j;
		}
		List<MenuEntity> listdad = crt.list();
		List<MenuEntity> listSon = crtSon.list();
		for (MenuEntity dad : listdad) {
			List<MenuEntity> list = new ArrayList<>();
			for (MenuEntity son : listSon) {
				if (son.getParentId().equals(dad.getId())) {
					list.add(son);
				}
			}
			dad.setNodes(list);
		}
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", listdad);
		return j;
	}

}
